﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Security.Authentication;

namespace AWA.VAT.EmailApp
{
    // TODO: Abstract to interface and rename this to GoogleEmailer
    public class Emailer
    {
        public void SendEmail(IEnumerable<string> emailAddresses, string subject, string message)
        {
            foreach (string emailAddress in emailAddresses)
            {
                try
                {
                    SendEmail(emailAddresses, subject, message);
                }
                catch (AuthenticationException)
                {
                    // raise message
                    break;
                }
            }
        }

        public void SendEmail(string emailAddress, string subject, string message)
        {
            // http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/28b5a576-0da2-42c9-8de3-f2bd1f30ded4
            // http://forums.asp.net/t/1402512.aspx/1

            MailMessage theEmail = new MailMessage();
            
            theEmail.To.Add(new MailAddress(emailAddress));
            theEmail.From = new MailAddress(Configuration.EmailUsername);
            theEmail.BodyEncoding = System.Text.Encoding.UTF8;
            theEmail.SubjectEncoding = System.Text.Encoding.UTF8;
            theEmail.Body = message;
            theEmail.Subject = subject;

            SmtpClient smtpClient = new SmtpClient(Configuration.SMTPHost, Configuration.SMTPPort);
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = new NetworkCredential(Configuration.EmailUsername, Configuration.EmailPassword);
            //smtp.Timeout = 2000;
            //smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;

#if DEBUG
            System.Diagnostics.Debug.WriteLine("Simulate SmtpClient.Send (5-15 seconds) to " + emailAddress);
            System.Threading.Thread.Sleep(5000);
#else
            smtpClient.Send(theEmail);
#endif
        }
    }
}
